﻿using UnityEngine;

public class SkeletonBattleState:SkeletonStateBase
{
    public SkeletonBattleState(ControllerBase controller, StateMachineBase stateMachine, string stateName,
        string animatorParameter = null) : base(controller, stateMachine, stateName, animatorParameter)
    {
    }

    //TODO:后续添加playerManger
    private Transform target;

    private int moveDir;
    public override void Enter()
    {
        base.Enter();
        target = PlayerManager.Instance.controller.transform;
    }

    public override void Exit()
    {
        base.Exit();
    }

    public override void Update()
    {
        base.Update();
        if (!CheckCanUpdate())
        {
            return;
        }
        if (SelfController.isFindTarget
            &&SelfController.hit.distance <SelfController.GetEnemyStateInfo().AttackTriggerDistance
            && CanAttack())
        {
            //进入攻击姿态攻击 
            stateMachine.ChangeState(Setting.attack);
            return;
        }
        
        //是否脱离仇恨区域或时间
        if (!SelfController.isFindTarget)
        {
            if (stateDuration>SelfController.GetEnemyStateInfo().BattleDuration
                ||Mathf.Abs(target.position.x - SelfController.transform.position.x)>SelfController.GetEnemyStateInfo().BattleDistance)
            {
                stateMachine.ChangeState(Setting.idle);
                return;
            }
        }


        if (Mathf.Abs(target.position.x-SelfController.transform.position.x)>0.1) //防止与玩家重合后来回翻转
        {
            
            if (target.position.x>SelfController.transform.position.x)
            {
                moveDir = 1;
            }else if (target.position.x<SelfController.transform.position.x)
            {
                moveDir = -1;
            }
            //继续移动
            SelfController.SetVelocity(new Vector2(SelfController.GetEnemyStateInfo().MoveSpeed*moveDir
                    , SelfController.GetVelocity().y));
        }
    }

    private bool CanAttack()
    {
        return Time.time - SelfController.lastAttackTime > SelfController.GetEnemyStateInfo().AttackCd;
    }
}